#include "CTimerManager.h"

std::auto_ptr<CTimerManager> CTimerManager::m_instance;

CTimerManager::CTimerManager()
{
    bPreventLowdown = true;
    Initialize();
}

CTimerManager::~CTimerManager()
{
}

bool CTimerManager::Release()
{
    return true;
}

void CTimerManager::Initialize()
{
    uiLastTime = SDL_GetTicks();
    fFrameTime = 0.0f;
    iFrameTime = 0;
    iFPS = 0;
    iFrameCount = 0;
    iTimeAcum = 0;
    iMaxInterval = 40;
    iMinInterval = 24;
}

void CTimerManager::SetInterval(int iMin, int iMax)
{
    iMaxInterval = iMax;
    iMinInterval = iMin;
}

void CTimerManager::Reset()
{
    uiLastTime = SDL_GetTicks();
}

int	 CTimerManager::GetFPS()
{
    return iFPS;
}

void CTimerManager::Update()
{
    iFrameTime = 0;
    unsigned int uiCurrentTime;

    do{
        uiCurrentTime	= SDL_GetTicks();
        iFrameTime		= (uiCurrentTime >  uiLastTime)? uiCurrentTime - uiLastTime : 0;
        uiLastTime		= (uiCurrentTime >= uiLastTime)? uiLastTime : uiCurrentTime;
    }
    while (!(iFrameTime >= iMinInterval));

    if (bPreventLowdown && (iFrameTime > iMaxInterval))
        iFrameTime = iMaxInterval;

    iTimeAcum  += iFrameTime;
    iFrameCount++;
    fFrameTime = (float)iFrameTime * 0.001f;

    if (iTimeAcum >= 1000){
        iFPS				= iFrameCount;
        iFrameCount = 0;
        iTimeAcum   = 0;
    }

    uiLastTime = uiCurrentTime;
}
